package dao.impl;
import java.sql.*;
import dao.UserDao;
import pojo.User;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    public List<User> findAll() {
        //jdbc查询数据库操作
        List<User> users = new ArrayList<>();
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String username = "root";
            String password = "989898";
            String url = "jdbc:mysql://localhost:3306/jdbc";
            // 建立连接
            conn = DriverManager.getConnection(url, username, password);
            // 创建SQL语句执行对象
            String sql="SELECT * FROM sys_user";
            preparedStatement = conn.prepareStatement(sql);
            // 执行查询语句
            resultSet = preparedStatement.executeQuery(sql);

            while (resultSet.next()) {
                User u = new User();
                u.setId(resultSet.getInt("id"));
                u.setName(resultSet.getString("name"));
                u.setPass(resultSet.getString("pass"));
                users.add(u);
                // 根据列名获取数据，这里假设表中有id和name两列
            }
            return users;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }finally{
            //关闭资源
            try{
                if(resultSet != null){
                    resultSet.close();
                }
                if(preparedStatement!=null){
                    preparedStatement.close();
                }
                if(conn != null){
                    conn.close();
                }
            }catch(SQLException e){
                throw new RuntimeException(e);
            }
        }
    }
}